# -*- coding: utf-8 -*-
"""
    APF.libs.plugin_base
    ~~~~~~~~~~~~~~
    插件基类
    :copyright: (c) 2018 XJJ by CornWu
"""
import os
import imp
from utils.log import Logger

__ModuleFunctions__ = {}
__CurrentModuleName__ = ''
__CurrentPluginName__ = ''

class PluginBase(object):
    def __init__(self, pluginName,pluginPath):
        super(PluginBase, self).__init__()
        self._pluginName = pluginName
        self._pluginPath = pluginPath
        self._logger = Logger("plugin_"+pluginName+"").getLogger

    #: 插件初始化
    def Initialize(self):
        #: 动态加载插件目录下的所有模块
        self.__scanPluginModules()

    #: 扫描插件下的模块
    def __scanPluginModules(self):
        """ 扫描插件目录 """
        self._logger.info("Initialization Plugin Modules Start, loadPluginModules path: {0}".format(self._pluginPath))
        if os.path.exists(self._pluginPath):
            for pluginModuleName in os.listdir(self._pluginPath):
                plugin_module_path = os.path.join(self._pluginPath, pluginModuleName)
                (moduleName, moduleExtension) = os.path.splitext(pluginModuleName)
                (filename, extension) = os.path.splitext(plugin_module_path)
                if os.path.isfile(plugin_module_path) and pluginModuleName <> '__init__.py' and extension == '.py':
                    self.__loadPluginModule(moduleName,plugin_module_path)
        else:
            self._logger.plugin.warning("Plugin directory not in here!")

    #: 加载插件下的模块
    def __loadPluginModule(self, pluginModuleName, pluginModuleFilePath):
        try:
            global __CurrentPluginName__
            __CurrentPluginName__ = self._pluginName
            global __CurrentModuleName__
            __CurrentModuleName__ = pluginModuleName
            pluginModule = imp.load_source("{0}{1}{2}".format("plugins", self._pluginName, pluginModuleName),pluginModuleFilePath)
        except Exception, e:
            self._logger.plugin.error("plugin package: load {0} module error,{1}".format(pluginModuleName, e))
            self._logger.plugin.exception(e, exc_info=True)

    #: 插件释放
    def Release(self):
        pass

    #: 插件激活
    def Activate(self):
        pass

    #: 插件解除
    def Deactivate(self):
        pass

    #: 插件关于信息
    def GetAbout(self):
        pass

    #: 插件功能列表
    def GetFuncList(self):
        return __ModuleFunctions__


def ModuleFunc(rule,**options):
    def decorator(func):
        if func is not None:
            url = "/{0}/{1}{2}".format(__CurrentPluginName__, __CurrentModuleName__, rule)
            old_func = __ModuleFunctions__.get(url)
            if old_func is None:
                #NeedAuth = options.pop('NeedAuth', True)
                #Methods = options.pop('Methods', ["GET"])
                Methods = ["POST"]
                ApiSpecs = options.pop('ApiSpecs', {})
                ApiOperation =  options.pop('ApiOperation', {
                    "Name": func.__name__,
                    "Description": func.__name__,
                    "NeedAuth": False
                })
                NeedAuth = ApiOperation["NeedAuth"]
                ApiParameter = options.pop('ApiParameter', None)
                ApiResponse = options.pop('ApiResponse', None)

                if ApiSpecs is not None:
                    ApiSpecs["tags"] = [
                        __CurrentPluginName__
                    ]

                __ModuleFunctions__[url] = {
                    "PluginName": __CurrentPluginName__,
                    "ModuleName": __CurrentModuleName__,
                    "FuncName": func.__name__,
                    "ModuleRule": rule,
                    "ModuleFunc": func,
                    "Methods": Methods,
                    "NeedAuth": NeedAuth,
                    "ApiSpecs": ApiSpecs,
                    "ApiOperation": ApiOperation,
                    "ApiParameter": ApiParameter,
                    "ApiResponse": ApiResponse
                }
        return func

    return decorator